package com.bestcem.xm.survey.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.xuyanwu.spring.file.storage.Downloader;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bestcem.xm.common.core.oss.enums.OssPathEnum;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.componet.filestorage.service.StorageService;
import com.bestcem.xm.survey.entity.SurveyRespondentWeixin;
import com.bestcem.xm.survey.job.SurveyJobService;
import com.bestcem.xm.survey.service.SurveyCommonService;
import com.bestcem.xm.survey.service.SurveyMessageReceiverService;
import com.bestcem.xm.survey.service.SurveyRespondentWeixinService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author SXS
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/test")
public class TestController {

    private @NonNull SurveyMessageReceiverService surveyMessageReceiverService;

    private @NonNull SurveyRespondentWeixinService weixinService;

    private @NonNull StorageService storageService;

    private @NonNull SurveyCommonService surveyCommonService;

    private @NonNull SurveyJobService surveyJobService;

    @AuthIgnore
    @GetMapping("/{id}")
    public void test(@PathVariable String id) {
        surveyMessageReceiverService.createQColumns(id);
    }

    @AuthIgnore
    @GetMapping
    public void test() throws Exception {
        String rid = "22";
        SurveyRespondentWeixin weixin = new SurveyRespondentWeixin();
        weixin.setProjectId("1111");
        weixin.setRid(rid);
        weixin.setWxSex(1);

        SurveyRespondentWeixin weixin2 = new SurveyRespondentWeixin();
        weixin2.setRid(rid);
        weixinService.saveOrUpdate(weixin,
                new LambdaQueryWrapper<>(weixin2));

        log.info(weixin.toString());

        log.info(weixin2.toString());
    }

    @AuthIgnore
    @GetMapping("/ref")
    public void ref() {
        //String url = storageService.getPropertiesValueBy(null, "domain");
        String url = storageService.getPropertiesValueBy("minio1", "domain") + storageService.getPropertiesValueBy("minio1", "base-path");
        System.out.println(url);
    }

    @AuthIgnore
    @GetMapping("/geturl")
    public void geturl() {
        final FileInfo byCondition = storageService.getByCondition("minio", "upload/", "64b60de707623b49641d0804.png");
        System.out.println(byCondition.getUrl());
    }

    @AuthIgnore
    @GetMapping("/saveunsubmitedanswer")
    public void saveUnsubmitedAnswer() {
        surveyJobService.saveUnsubmitedAnswer();
    }

    @AuthIgnore
    @GetMapping("/upload/upload")
    public void upload() {
        String url = storageService.upload(new File("C:/Users/been/Downloads/基线版架构图.png"), "架构图", "upload/", new Dict()).getUrl();
        System.out.println(url);
    }

    @AuthIgnore
    @GetMapping("/excel")
    public void excel(HttpServletResponse response) {
        List<List<List<String>>> head = new ArrayList<>();
        List<List<String>> headRowList = new ArrayList<>();

        List<List<List<String>>> exportDataList = new ArrayList<>();
        List<List<String>> rowList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            List<String> exportItem = new ArrayList<>();
            exportItem.add("微信OpenID" + (i + 1));
            exportItem.add("微信昵称" + (i + 1));
            exportItem.add("问卷链接" + (i + 1));
            exportItem.add("发送状态" + (i + 1));
            exportItem.add("发送时间" + (i + 1));
            exportItem.add("答卷状态" + (i + 1));
            rowList.add(exportItem);
        }
        getTitleHead(headRowList, Stream.of("微信OpenID", "微信昵称", "问卷链接", "发送状态", "发送时间", "答卷状态").collect(Collectors.toList()));

        head.add(headRowList);
        exportDataList.add(rowList);
        // sheet页名称-自定义，如果没有则传空
        List<String> sheetNameList = Stream.of("sheet1").collect(Collectors.toList());
        String ossPath = OssPathEnum.TEMP_DELIVER.getPath() + "emaildeliver/export/" + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + "/";
        String fileName = "投放清单明细";

        //数据准备完毕,生成本地临时文件
        //File exportFile = ExcelExportUtil.exportWithDynamicData2LocalDir(fileName, head, exportDataList, sheetNameList);
        ////上传到oss
        //String url = storageService.upload(exportFile, Objects.requireNonNull(exportFile).getName(), ossPath, new Dict()).getUrl();
        //System.out.println(url);
        //ExcelExportUtil.downloadTemplate(exportFile.getPath(), fileName, ExcelExportUtil.XLSX_SUFFIX, response);
        //exportFile.delete();
        final String url = surveyCommonService.exportWithDynamicData(fileName, head, exportDataList, sheetNameList, response, ossPath).getValue0();
        System.out.println(url);
    }

    @AuthIgnore
    @GetMapping("/size")
    public void size() {
        //Downloader downloader = storageService.downloadByUrl("http://127.0.0.1:9000/bestcem/test/rs/temp/deliver/ds/emaildeliver/export/20230719163318/投放清单明细.xlsx");
        Downloader downloader = storageService.downloadByUrl("http://127.0.0.1:9000/bestcem/test/rs/temp/deliver/ds/emaildeliver/export/20230719163318/11投放清单明细.xlsx");
        if (Objects.nonNull(downloader)) {
            try (InputStream inputStream = new ByteArrayInputStream(downloader.bytes())) {
                // 读取数据
                ExcelReader excelReader = ExcelUtil.getReader(inputStream);
                List<List<Object>> read = excelReader.read(1, excelReader.getRowCount());
                for (List<Object> objects : read) {
                    log.error(Convert.toStr(objects.get(0)));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void getTitleHead(List<List<String>> headRowList, List<String> titelList) {
        for (String title : titelList) {
            List<String> rowHead = new ArrayList<>();
            rowHead.add(title);
            headRowList.add(rowHead);
        }
    }
}